package com.diaohw.platform.remote.log.netty;

import com.diaohw.platform.common.LogProcessAPI;
import com.diaohw.platform.common.enums.NettyTypeEnum;
import com.diaohw.platform.common.obj.log.DbLog;
import com.diaohw.platform.common.obj.log.RequestLog;
import com.diaohw.platform.utility.netty.NettyClient;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Service
@ChannelHandler.Sharable
@ConditionalOnProperty("platform.remote.log.netty.enable")
public class NettyLogProcess extends SimpleChannelInboundHandler<String> implements LogProcessAPI {

    private static final ExecutorService executor = Executors.newCachedThreadPool();

    @Resource
    private NettyLogProperties properties;

    private NettyClient client;

    @PostConstruct
    public void init() {
        client = new NettyClient(properties.getPort(), properties.getHost());
        client.connect(this);
    }

    @Override
    public void http(RequestLog requestLog) {
        executor.execute(() -> sendMessage(NettyTypeEnum.HTTP_LOG, requestLog));
    }

    @Override
    public void db(DbLog dbLog) {
        executor.execute(() -> sendMessage(NettyTypeEnum.DB_LOG, dbLog));
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.debug("收到服务端消息： {}", msg);
    }

    private void sendMessage(NettyTypeEnum type, Object obj) {
        String build = type.encode(obj);
        client.sendMessage(build);
    }

}
